package jaux.tank.api.controller.system;

import java.util.List;
import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import jaux.tank.api.controller.BaseController;
import jaux.tank.bean.annotion.core.BussinessLog;
import jaux.tank.bean.dictmap.DeptDict;
import jaux.tank.bean.dto.DeptDto;
import jaux.tank.bean.entity.system.Dept;
import jaux.tank.bean.enumeration.BizExceptionEnum;
import jaux.tank.bean.exception.TankException;
import jaux.tank.bean.vo.front.Ret;
import jaux.tank.bean.vo.front.Rets;
import jaux.tank.bean.vo.node.DeptNode;
import jaux.tank.dao.system.DeptRepository;
import jaux.tank.service.system.DeptService;
import jaux.tank.utils.ToolUtil;

/**
 * DeptContoller
 *
 * @author zt
 * @version 2018/9/15 0015
 */
@RestController("deptApiController")
@RequestMapping("/api/dept")
public class DeptContoller extends BaseController {
    private Logger logger = LoggerFactory.getLogger(DeptContoller.class);
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private DeptService deptService;
    @ApiOperation(value = "查询所有部门")
    @GetMapping("/list")
    public Ret<List<DeptNode>> list(){
        List<DeptNode> list = deptService.queryAll();
        return Rets.success(list);
    }
    
    @ApiOperation("查询指定部门及下级部门")
    @GetMapping("/queryRootAndSubDepts")
    public Ret<List<Dept>> queryRootAndSubDepts(@RequestParam String deptId){
    	Optional<Dept> root = deptRepository.findById(deptId);
    	List<Dept> subDepts = deptService.querySubDepts(deptId);
    	if(subDepts!=null && root.isPresent()) {
    		subDepts.add(root.get());
    	}
		return Rets.success(subDepts);
    }
    
    @ApiOperation(value = "编辑部门")
    @PostMapping
    @BussinessLog(value = "编辑部门", key = "simplename", dict = DeptDict.class)
    public Ret<Object> save(@ModelAttribute DeptDto dept){
        if (ToolUtil.isOneEmpty(dept, dept.getSimplename())) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        deptRepository.save(dept.toEntity());
        return Rets.success();
    }
    @ApiOperation(value = "删除部门")
    @DeleteMapping
    @BussinessLog(value = "删除部门", key = "id", dict = DeptDict.class)
    public Ret<Object> remove(String id){
        logger.info("id:{}",id);
        if (ToolUtil.isEmpty(id)) {
            throw new TankException(BizExceptionEnum.REQUEST_NULL);
        }
        deptService.deleteDept(id);
        return Rets.success();
    }
}
